package com.selectphoto;

import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.Webcam;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.IOException;

/**
 * 相机测试
 */
public class CallCamera {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // 得保证先执行该语句，用于加载库，才能调用其他操作库的语句，
    }

    public static Mat selectpng() throws IOException {

        Webcam webcams = Webcam.getDefault();
        webcams.setViewSize(WebcamResolution.VGA.getSize());    //改变图片分辨率
        webcams.open();
        //String fina = "photo/select" + System.currentTimeMillis() % 100 + ".png";
        //File file = new File(fina);
        //ImageIO.write(webcams.getImage(), "PNG", file); //保存图片
        // 如果它已经具有正确的类型，则不要转换
        if (webcams.getImage().getType() != BufferedImage.TYPE_4BYTE_ABGR) {

            // 创建缓存图像
            BufferedImage image = new BufferedImage(webcams.getImage().getWidth(), webcams.getImage().getHeight(), BufferedImage.TYPE_3BYTE_BGR);

            // 将图像绘制到新缓存区
            Graphics2D g = image.createGraphics();
            try {
                g.setComposite(AlphaComposite.Src);
                g.drawImage(webcams.getImage(), 0, 0, null);
            } finally {
                g.dispose();
            }
        }
        DataBufferByte dbi = (DataBufferByte) webcams.getImage().getRaster().getDataBuffer();
        byte[] pixels = dbi.getData();
        Mat mat = Mat.eye(webcams.getImage().getHeight(), webcams.getImage().getWidth(), CvType.CV_8UC3);
        webcams.close();    //关闭Webcam并清空内存中的缓存图
        mat.put(0, 0, pixels);
        return mat;
    }
}
